<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI战争模拟器</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            min-height: 100vh;
        }
        .battle-grid {
            display: grid;
            grid-template-columns: repeat(10, 1fr);
            gap: 2px;
            background: #2d3748;
            padding: 10px;
            border-radius: 8px;
        }
        .grid-cell {
            aspect-ratio: 1;
            background: #4a5568;
            border: 1px solid #718096;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .grid-cell:hover {
            background: #718096;
        }
        .red-unit {
            background: #e53e3e;
            color: white;
        }
        .blue-unit {
            background: #3182ce;
            color: white;
        }
        .empty-cell {
            background: #4a5568;
        }
        .battle-log {
            max-height: 300px;
            overflow-y: auto;
            background: #2d3748;
            color: white;
            padding: 10px;
            border-radius: 8px;
            font-family: monospace;
            font-size: 12px;
        }
        .unit-info {
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 5px;
            border-radius: 4px;
            font-size: 10px;
            position: absolute;
            z-index: 10;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="container mx-auto px-4 py-8">
        <h1 class="text-4xl font-bold text-white text-center mb-8">AI战争模拟器</h1>
        
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
            <!-- 左侧兵力信息 -->
            <div class="bg-white bg-opacity-10 rounded-lg p-4">
                <h2 class="text-xl font-bold text-white mb-4">兵力对比</h2>
                <div class="space-y-4">
                    <div>
                        <h3 class="text-red-300 font-semibold">红方军队</h3>
                        <div class="w-full bg-gray-700 rounded-full h-4">
                            <div id="red-bar" class="bg-red-500 h-4 rounded-full transition-all duration-300" style="width: 100%"></div>
                        </div>
                        <p class="text-white text-sm mt-1">兵力: <span id="red-count">100</span></p>
                    </div>
                    <div>
                        <h3 class="text-blue-300 font-semibold">蓝方军队</h3>
                        <div class="w-full bg-gray-700 rounded-full h-4">
                            <div id="blue-bar" class="bg-blue-500 h-4 rounded-full transition-all duration-300" style="width: 100%"></div>
                        </div>
                        <p class="text-white text-sm mt-1">兵力: <span id="blue-count">100</span></p>
                    </div>
                </div>
                
                <div class="mt-6">
                    <h3 class="text-white font-semibold mb-2">回合信息</h3>
                    <p class="text-white text-sm">当前回合: <span id="current-turn">0</span></p>
                    <p class="text-white text-sm">阶段: <span id="current-phase">准备中</span></p>
                </div>
                
                <div class="mt-6 space-y-2">
                    <button id="start-btn" class="w-full bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded">
                        开始战争
                    </button>
                    <button id="reset-btn" class="w-full bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded">
                        重置战场
                    </button>
                </div>
            </div>
            
            <!-- 中间战场 -->
            <div class="lg:col-span-2">
                <div class="bg-white bg-opacity-10 rounded-lg p-4">
                    <h2 class="text-xl font-bold text-white mb-4 text-center">战场沙盘</h2>
                    <div class="battle-grid" id="battle-grid"></div>
                </div>
            </div>
            
            <!-- 右侧战报 -->
            <div class="bg-white bg-opacity-10 rounded-lg p-4">
                <h2 class="text-xl font-bold text-white mb-4">战报</h2>
                <div class="battle-log" id="battle-log">
                    <div>战争即将开始...</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        class BattleSimulator {
            constructor() {
                this.gridSize = 10;
                this.grid = [];
                this.redArmy = [];
                this.blueArmy = [];
                this.currentTurn = 0;
                this.isRunning = false;
                this.turnInterval = null;
                
                this.initializeGrid();
                this.bindEvents();
            }
            
            initializeGrid() {
                const gridContainer = document.getElementById('battle-grid');
                gridContainer.innerHTML = '';
                
                this.grid = Array(this.gridSize).fill(null).map(() => Array(this.gridSize).fill(null));
                
                for (let row = 0; row < this.gridSize; row++) {
                    for (let col = 0; col < this.gridSize; col++) {
                        const cell = document.createElement('div');
                        cell.className = 'grid-cell empty-cell';
                        cell.dataset.row = row;
                        cell.dataset.col = col;
                        cell.addEventListener('mouseenter', (e) => this.showUnitInfo(e));
                        cell.addEventListener('mouseleave', () => this.hideUnitInfo());
                        gridContainer.appendChild(cell);
                    }
                }
            }
            
            bindEvents() {
                document.getElementById('start-btn').addEventListener('click', () => this.startWar());
                document.getElementById('reset-btn').addEventListener('click', () => this.resetBattle());
            }
            
            showUnitInfo(event) {
                const cell = event.target;
                const row = parseInt(cell.dataset.row);
                const col = parseInt(cell.dataset.col);
                const unit = this.grid[row][col];
                
                if (unit) {
                    const info = document.createElement('div');
                    info.className = 'unit-info';
                    info.innerHTML = `
                        ${unit.type}<br>
                        兵力: ${unit.strength}<br>
                        士气: ${unit.morale}
                    `;
                    info.style.left = event.pageX + 10 + 'px';
                    info.style.top = event.pageY + 10 + 'px';
                    document.body.appendChild(info);
                }
            }
            
            hideUnitInfo() {
                const info = document.querySelector('.unit-info');
                if (info) info.remove();
            }
            
            startWar() {
                if (this.isRunning) return;
                
                this.isRunning = true;
                this.currentTurn = 0;
                this.redArmy = [];
                this.blueArmy = [];
                
                // 初始布阵
                this.deployArmies();
                this.updateDisplay();
                
                this.addLog('战争开始！红方与蓝方军队已部署完毕。');
                
                // 开始回合制战斗
                this.turnInterval = setInterval(() => {
                    this.executeTurn();
                }, 1000);
            }
            
            deployArmies() {
                // 红方布阵（左侧）
                for (let i = 0; i < 5; i++) {
                    const unit = {
                        type: '步兵',
                        strength: 20,
                        morale: 100,
                        side: 'red',
                        row: Math.floor(Math.random() * this.gridSize),
                        col: Math.floor(Math.random() * 3)
                    };
                    this.redArmy.push(unit);
                    this.grid[unit.row][unit.col] = unit;
                }
                
                // 蓝方布阵（右侧）
                for (let i = 0; i < 5; i++) {
                    const unit = {
                        type: '步兵',
                        strength: 20,
                        morale: 100,
                        side: 'blue',
                        row: Math.floor(Math.random() * this.gridSize),
                        col: this.gridSize - 1 - Math.floor(Math.random() * 3)
                    };
                    this.blueArmy.push(unit);
                    this.grid[unit.row][unit.col] = unit;
                }
            }
            
            executeTurn() {
                this.currentTurn++;
                document.getElementById('current-turn').textContent = this.currentTurn;
                
                // 阶段1：召集民兵
                this.recruitMilitia();
                
                // 阶段2：移动
                this.moveUnits();
                
                // 阶段3：战斗
                this.combatPhase();
                
                // 检查胜负
                if (this.checkVictory()) {
                    this.endWar();
                }
                
                this.updateDisplay();
            }
            
            recruitMilitia() {
                document.getElementById('current-phase').textContent = '召集民兵';
                
                // 每方每回合有概率获得民兵
                if (Math.random() < 0.3) {
                    const newUnit = {
                        type: '民兵',
                        strength: 10,
                        morale: 80,
                        side: 'red',
                        row: Math.floor(Math.random() * this.gridSize),
                        col: 0
                    };
                    
                    if (!this.grid[newUnit.row][newUnit.col]) {
                        this.redArmy.push(newUnit);
                        this.grid[newUnit.row][newUnit.col] = newUnit;
                        this.addLog('红方获得民兵增援！');
                    }
                }
                
                if (Math.random() < 0.3) {
                    const newUnit = {
                        type: '民兵',
                        strength: 10,
                        morale: 80,
                        side: 'blue',
                        row: Math.floor(Math.random() * this.gridSize),
                        col: this.gridSize - 1
                    };
                    
                    if (!this.grid[newUnit.row][newUnit.col]) {
                        this.blueArmy.push(newUnit);
                        this.grid[newUnit.row][newUnit.col] = newUnit;
                        this.addLog('蓝方获得民兵增援！');
                    }
                }
            }
            
            moveUnits() {
                document.getElementById('current-phase').textContent = '部队移动';
                
                // 红方移动（向右）
                this.redArmy.forEach(unit => {
                    if (unit.strength > 0 && unit.col < this.gridSize - 1) {
                        const newCol = Math.min(unit.col + 1, this.gridSize - 1);
                        if (!this.grid[unit.row][newCol]) {
                            this.grid[unit.row][unit.col] = null;
                            unit.col = newCol;
                            this.grid[unit.row][unit.col] = unit;
                        }
                    }
                });
                
                // 蓝方移动（向左）
                this.blueArmy.forEach(unit => {
                    if (unit.strength > 0 && unit.col > 0) {
                        const newCol = Math.max(unit.col - 1, 0);
                        if (!this.grid[unit.row][newCol]) {
                            this.grid[unit.row][unit.col] = null;
                            unit.col = newCol;
                            this.grid[unit.row][newCol] = unit;
                        }
                    }
                });
            }
            
            combatPhase() {
                document.getElementById('current-phase').textContent = '战斗阶段';
                
                // 检查相邻的敌对单位进行战斗
                for (let row = 0; row < this.gridSize; row++) {
                    for (let col = 0; col < this.gridSize; col++) {
                        const unit = this.grid[row][col];
                        if (unit && unit.strength > 0) {
                            // 检查周围的敌人
                            const enemies = this.findAdjacentEnemies(row, col, unit.side);
                            if (enemies.length > 0) {
                                // 随机选择一个敌人战斗
                                const enemy = enemies[Math.floor(Math.random() * enemies.length)];
                                this.battle(unit, enemy);
                            }
                        }
                    }
                }
            }
            
            findAdjacentEnemies(row, col, side) {
                const enemies = [];
                const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
                
                for (const [dr, dc] of directions) {
                    const newRow = row + dr;
                    const newCol = col + dc;
                    
                    if (newRow >= 0 && newRow < this.gridSize && 
                        newCol >= 0 && newCol < this.gridSize) {
                        const enemy = this.grid[newRow][newCol];
                        if (enemy && enemy.side !== side && enemy.strength > 0) {
                            enemies.push(enemy);
                        }
                    }
                }
                
                return enemies;
            }
            
            battle(unit1, unit2) {
                const damage1 = Math.floor(Math.random() * unit1.strength * 0.5) + 1;
                const damage2 = Math.floor(Math.random() * unit2.strength * 0.5) + 1;
                
                unit2.strength = Math.max(0, unit2.strength - damage1);
                unit1.strength = Math.max(0, unit1.strength - damage2);
                
                this.addLog(`${unit1.side === 'red' ? '红方' : '蓝方'}${unit1.type}与${unit2.side === 'red' ? '红方' : '蓝方'}${unit2.type}交战！`);
                
                if (unit2.strength <= 0) {
                    this.addLog(`${unit2.side === 'red' ? '红方' : '蓝方'}${unit2.type}被消灭！`);
                    this.grid[unit2.row][unit2.col] = null;
                }
                
                if (unit1.strength <= 0) {
                    this.addLog(`${unit1.side === 'red' ? '红方' : '蓝方'}${unit1.type}被消灭！`);
                    this.grid[unit1.row][unit1.col] = null;
                }
            }
            
            checkVictory() {
                const redAlive = this.redArmy.filter(u => u.strength > 0).length;
                const blueAlive = this.blueArmy.filter(u => u.strength > 0).length;
                
                return redAlive === 0 || blueAlive === 0 || this.currentTurn >= 50;
            }
            
            endWar() {
                clearInterval(this.turnInterval);
                this.isRunning = false;
                
                const redAlive = this.redArmy.filter(u => u.strength > 0).length;
                const blueAlive = this.blueArmy.filter(u => u.strength > 0).length;
                
                let winner;
                if (redAlive > blueAlive) {
                    winner = '红方';
                } else if (blueAlive > redAlive) {
                    winner = '蓝方';
                } else {
                    winner = '平局';
                }
                
                this.addLog(`战争结束！${winner}获胜！`);
                alert(`战争结束！${winner}获胜！`);
            }
            
            resetBattle() {
                clearInterval(this.turnInterval);
                this.isRunning = false;
                this.currentTurn = 0;
                this.redArmy = [];
                this.blueArmy = [];
                
                document.getElementById('current-turn').textContent = '0';
                document.getElementById('current-phase').textContent = '准备中';
                document.getElementById('red-count').textContent = '0';
                document.getElementById('blue-count').textContent = '0';
                document.getElementById('red-bar').style.width = '0%';
                document.getElementById('blue-bar').style.width = '0%';
                
                document.getElementById('battle-log').innerHTML = '<div>战争即将开始...</div>';
                
                this.initializeGrid();
            }
            
            updateDisplay() {
                // 更新网格显示
                const cells = document.querySelectorAll('.grid-cell');
                cells.forEach(cell => {
                    cell.className = 'grid-cell empty-cell';
                });
                
                // 显示红方单位
                this.redArmy.forEach(unit => {
                    if (unit.strength > 0) {
                        const cell = document.querySelector(`[data-row="${unit.row}"][data-col="${unit.col}"]`);
                        if (cell) {
                            cell.className = 'grid-cell red-unit';
                            cell.textContent = unit.strength;
                        }
                    }
                });
                
                // 显示蓝方单位
                this.blueArmy.forEach(unit => {
                    if (unit.strength > 0) {
                        const cell = document.querySelector(`[data-row="${unit.row}"][data-col="${unit.col}"]`);
                        if (cell) {
                            cell.className = 'grid-cell blue-unit';
                            cell.textContent = unit.strength;
                        }
                    }
                });
                
                // 更新兵力条
                const redTotal = this.redArmy.reduce((sum, u) => sum + u.strength, 0);
                const blueTotal = this.blueArmy.reduce((sum, u) => sum + u.strength, 0);
                
                document.getElementById('red-count').textContent = redTotal;
                document.getElementById('blue-count').textContent = blueTotal;
                
                const maxStrength = 200;
                document.getElementById('red-bar').style.width = `${(redTotal / maxStrength) * 100}%`;
                document.getElementById('blue-bar').style.width = `${(blueTotal / maxStrength) * 100}%`;
            }
            
            addLog(message) {
                const log = document.getElementById('battle-log');
                const entry = document.createElement('div');
                entry.textContent = `[回合${this.currentTurn}] ${message}`;
                log.appendChild(entry);
                log.scrollTop = log.scrollHeight;
            }
        }
        
        // 初始化模拟器
        const simulator = new BattleSimulator();
    </script>
</body>
</html>